import { createApp } from 'vue'
import App from './App.vue'
import store from "./store/index"
import router from "./router/index"
import axios from "axios"
import { Overlay, Checkbox, CheckboxGroup, DropdownMenu, DropdownItem, Button, IndexBar, Swipe, SwipeItem, Icon, Progress, Loading, Field, CellGroup  } from "vant"
import { Toast } from 'vant';
import ElementPlus from 'element-plus'
import { ElLoading } from 'element-plus'
import 'element-plus/dist/index.css'

const app = createApp(App);
app.use(Overlay)
app.use(Checkbox)
app.use(CheckboxGroup)
app.use(DropdownMenu)
app.use(DropdownItem)
app.use(Button)
app.use(IndexBar)
app.use(Swipe)
app.use(SwipeItem)
app.use(Icon)
app.use(Progress)
app.use(Loading)
app.use(Field);
app.use(CellGroup);


app.use(store)
app.use(router)
app.use(ElementPlus)


app.mount('#app')


axios.defaults.baseURL = "http://localhost:3000"
axios.defaults.timeout = 10000;
// 设置全局的请求次数，请求的间隙
axios.defaults.retry = 2;
axios.defaults.retryDelay = 1000;

// 添加请求拦截器
let loadingInstance;
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    loadingInstance = ElLoading.service({ fullscreen: true })
    return config;
}, function (error) {
    // 对请求错误做些什么
    Toast("请求错误")
    return console.log("请求错误" + error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    loadingInstance.close()
    return response;
}, async function (err) {
    // 对响应错误做点什么
    // 关闭加载框
    loadingInstance.close()
    // 失败处理
    let config = err.config;
    // 如果config不存在或没有设置重试选项，则拒绝 
    if (!config || !config.retry) return Promise.reject(err);
    // 设置用于跟踪重试计数的变量 
    config.__retryCount = config.__retryCount || 0;

    // 检查我们是否已经把重试的总次数加到了最大值 
    if (config.__retryCount >= config.retry) {
        // 拒绝错误
        Toast("请求超时!")
        return Promise.reject(err);
    }

    // 增加重试次数
    config.__retryCount += 1;

    // 创造新的Promise来处理指数后退 
    let backoff = new Promise(function (resolve) {
        setTimeout(function () {
            resolve();
        }, config.retryDelay || 1);
    });

    // 返回调用axios以重试请求的创造新的Promise来处理指数后退
    await backoff
    return await axios(config)
});
